package com.bawei.login


import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.entity.MovieVideoEntity
import com.bawei.common.event.LiveDataBus
import com.bawei.common.event.LiveDataBusEvent
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.login.databinding.ActivityLoginBinding
import com.bawei.login.entity.UserEntity
import com.bawei.login.intent.AccountViewIntent
import com.bawei.login.state.AccountUiState
import com.bawei.login.vm.AccountViewModel
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch


@Route(path = RoutePath.PATH_LOGIN_PAGE)
@AndroidEntryPoint
class LoginActivity : BaseMviActivity<ActivityLoginBinding>() {

    private val mViewModel: AccountViewModel by viewModels()

    private var userName = ""
    private var password = ""


    override fun getLayoutId(): Int = R.layout.activity_login

    override fun initViews() {
        mDataBinding.includedTitle.ivBack.setOnClickListener {
            this@LoginActivity.finish()
        }
        mDataBinding.includedTitle.tvTitle.text = "登录"

        //给输入框添加监听事件
        mDataBinding.etAccount.addTextChangedListener {
            userName = it.toString().trim()
        }
        mDataBinding.etPassword.addTextChangedListener {
            password = it.toString().trim()
        }

        //登录的点击事件
        mDataBinding.tvLoginBtn.setOnClickListener {
            loginToServer()
        }
        //注册新账号
        mDataBinding.tvRegisterBtn.setOnClickListener {
            ARouter.getInstance().build(RoutePath.PATH_REGISTER_PAGE).navigation()
        }

        LiveDataBus.with<LiveDataBusEvent>("login_page_new_account").observe(this@LoginActivity){
            handLiveDataEvent(it)
        }
    }

    private fun handLiveDataEvent(event: LiveDataBusEvent) {
        var user = event.data as UserEntity
        when(event.type){
            101 ->{
                mDataBinding.etAccount.setText(user.username)
                mDataBinding.etPassword.setText(user.password)
            }
        }
    }


    private fun loginToServer() {
        //校验一下输入的内容
        if (userName.isNullOrEmpty() || password.isNullOrEmpty()){
            showToastMsg("账号密码不能为空！")
            return
        }

        //开启协程发送意图
        lifecycleScope.launch {
            mViewModel.channel.send(AccountViewIntent.LoginToServer(userName, password))
        }
    }

    override suspend fun collectUiState() {
       mViewModel.uiState.collect{
           when(it){
               is AccountUiState.LoginToServerSuccess -> saveUserInfo(it.userEntity)
               is AccountUiState.LoginToServerFail -> showToastMsg(it.msg)
               else -> {}
           }
       }
    }

    private fun saveUserInfo(userEntity: UserEntity) {
        //保存用户信息
        MMKV.defaultMMKV().encode("userInfo", userEntity.toString())
        //保存Token信息
        if (!userEntity.token.isNullOrEmpty()){
            MMKV.defaultMMKV().encode("token", userEntity.token)
        }

        //关闭当期页面
        this@LoginActivity.finish()

    }


}